<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Category;
use App\Models\CookbookCollect;
use Illuminate\Http\Request;

class CookbookCollectController extends BaseController
{

    public $model = CookbookCollect::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $title = $request->input('title');

        $users = CookbookCollect::title($title)->withCount('cookbook')->orderBy("id", "desc")
                ->paginate(\request('per_page', 20));
        return $this->paginate($users);
    }

    public function info(Request $request) {
        $model = new $this->model;
        $table = $model->getTable();
        $this->validate($request, [
            'id' => 'required|exists:' . $table . ",id"
        ]);
        $id = \request("id");
        $info = $this->model::withCertain('cookbook', ['title', 'video_url', 'comment_num', 'star_num', 'category_id', 'type'])->find($id);
        if (!$info)
            return $this->failed('集合不存在');

        $arr = $info->toArray();
        $cookbook = $arr['cookbook'];
        foreach ($cookbook as &$item) {
            $item['category'] = Category::find($item['category_id'])->title ?? '';
        }
        unset($info['cookbook']);
        $info['cookbook'] = $cookbook;
        return $this->success($info);
    }


    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $model = CookbookCollect::find($id);
            if (!$model)
                return $this->failed('集合不存在');

            $model->tags()->sync([]);
        }
        return $this->success([], '删除成功');
    }

    public function store(Request $request) {
        $this->validate($request, [
            'title' => 'required',
            'cookbook_ids' => 'required',
        ]);
        $input = $request->input();
        try {
            \DB::transaction(function () use($input) {
                $arr_cookbook_id = explode(",", $input['cookbook_ids']);
                $id = $input['id'] ?? 0;
                if ($id) {
                    $model = CookbookCollect::find($id);
                    if (!$model)
                        return $this->failed('集合不存在');
                    $model->title = $input['title'];
                    $model->save();

                } else {
                    $model = CookbookCollect::create([
                        'title' => $input['title']
                    ]);
                }

                $model->cookbook()->sync($arr_cookbook_id);
            });
            return $this->success([], '修改成功');
        } catch (\Exception $e) {
            \Log::error($e);
            return $this->failed($e->getMessage());
        }

    }

}

